package com.china08.yxyapi.api.manage.tec.office.moments;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.mg.moments.YxyMoments;
import com.china08.yxyapi.entity.mg.moments.YxyMomentsComment;
import com.china08.yxyapi.model.YxyApiPageReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.mg.moments.YxyMomentsCommentRepository;
import com.china08.yxyapi.repository.mg.moments.YxyMomentsPraiseRepository;
import com.china08.yxyapi.repository.mg.moments.YxyMomentsRepository;
import com.china08.yxyapi.security.profile.YxyProfile;
import com.china08.yxyapi.util.DateToolUtils;
import com.china08.yxyapi.util.ThumborUtil;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

/**
 * 班级圈--查看全部发布/我的发布
 * 
 * @author LiuWeidong
 *
 */
@CrossOrigin
@RestController("MomentViewReleaseV2Controller")
public class MomentsViewReleaseV2Controller extends YxyApiBaseController {

    @Autowired
    private YxyMomentsRepository yxyMomentsRepository;

    @Autowired
    private YxyMomentsCommentRepository yxyMomentsCommentRepository;

    @Autowired
    private YxyMomentsPraiseRepository yxyMomentsPraiseRepository;

    @RequestMapping(value = "/api_yw/manage/tec/office/student/srh/release/view/v2", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Page<RespModel> precess(HttpServletRequest request, HttpServletResponse response, @RequestBody(required = true) ReqModel reqModel, RespModel respModel) {

        YxyProfile yxyProfile = getProfile(request, response);
        // 用户ID
        String currentUserId = yxyProfile.getId();
        System.out.println("用户ID:" + currentUserId);
        String schoolId = yxyProfile.getSchoolId();
        Integer type = reqModel.type;
        System.out.println("类型:" + type);
        List<String> classIdLst = reqModel.classIdLst;
        System.out.println("班级ID集合:" + classIdLst);
        String classId = reqModel.classId;
        System.out.println("班级ID:" + classId);
        Assert.isTrue(StringUtils.isNotBlank(classId) || classIdLst.size() != 0, "该老师没有关联班级，无法查看班级圈！");
        Pageable pageable = reqModel.getPageable(Direction.DESC, "createdDate");
        Page<YxyMoments> page = null;

        // type 类型 -0 全部 1 我的发布
        if (type == 0) {// 全部
            if (classIdLst != null && classIdLst.size() > 0) {// 查询全部
                page = yxyMomentsRepository.findBySchoolIdAndClassIdInAndStatusOrderByCreatedDateDesc(schoolId, classIdLst, 1, pageable);
            }
            if (classId != null && !"".equals(classId)) {// 查询某个班级
                page = yxyMomentsRepository.findBySchoolIdAndClassIdAndStatusOrderByCreatedDateDesc(schoolId, classId, 1, pageable);
            }
        } else {// 我的发布
            if (classIdLst != null && classIdLst.size() > 0) {// 查询全部
                page = yxyMomentsRepository.findBySchoolIdAndClassIdInAndSenderIdAndStatusOrderByCreatedDateDesc(schoolId, classIdLst, currentUserId, 1, pageable);
            }
            if (classId != null && !"".equals(classId)) {// 查询某个班级
                page = yxyMomentsRepository.findBySchoolIdAndClassIdAndSenderIdAndStatusOrderByCreatedDateDesc(schoolId, classId, currentUserId, 1, pageable);
            }
        }

        // 2. 转存在model中
        List<RespModel> respModelLst = new ArrayList<RespModel>();
        List<YxyMomentsCommentModel> yxyMomentsCommentLst = new ArrayList<YxyMomentsCommentModel>();
        List<YxyMomentsComment> yxyMomentsComment = new ArrayList<YxyMomentsComment>();
        // YxyMomentsCommentModel yxyMomentsCommentModel = null;
        List<YxyMomentsCommentModel> yxyMomentsCommentModelLst = null;

        if (page != null) {
            for (YxyMoments yxyMoments : page) {
                respModel = new RespModel();
                String momentsId = yxyMoments.getId();
                respModel.id = momentsId;
                respModel.createdDate = DateToolUtils.format(yxyMoments.getCreatedDate(), "yyyy-MM-dd HH:mm");
                respModel.senderId = yxyMoments.getSenderId();
                respModel.senderNick = yxyMoments.getSenderNick();
                respModel.classNick = yxyMoments.getClassNick();
                respModel.senderUsername = yxyMoments.getSenderUsername();
                respModel.styleIntro = yxyMoments.getStyleIntro();

                // 图片处理
                List<String> imgList = yxyMoments.getImgs();
                List<String> imgs_60_60 = new ArrayList<String>();
                if (imgList.size()>0) {
                    for (String string : imgList) {
                        string = ThumborUtil.resize(string, 60, 60);
                        imgs_60_60.add(string);
                    }
                }
                respModel.imgs_60_60 = imgs_60_60;
                respModel.status = yxyMoments.getStatus();

                // 评论数量
                YxyMoments moments = yxyMomentsRepository.findById(momentsId);
                if (moments != null) {
                    Integer count = yxyMomentsCommentRepository.countByMomentsId(momentsId);
                    moments.setCommentCount(count);
                    yxyMomentsRepository.save(moments);

                }
                respModel.commentCount = moments.getCommentCount() != null ? moments.getCommentCount() : 0;
                respModel.praiseCount = yxyMoments.getPraiseCount() != null ? yxyMoments.getPraiseCount() : 0;//
                respModel.praiseUserNickStr = yxyMoments.getPraiseUserNickStr("、 ");
                respModel.avator = yxyMoments.getAvatar();
                respModel.ownMoments = currentUserId.equals(yxyMoments.getSenderId());
                if (yxyMoments.getImgs() != null) {
                    respModel.imgSize = yxyMoments.getImgs().size();
                }
                // 是否点赞
                respModel.praise = yxyMomentsPraiseRepository.countByMomentsIdAndUserId(momentsId, currentUserId) > 0;
                //
                yxyMomentsCommentLst = new ArrayList<YxyMomentsCommentModel>();
                yxyMomentsComment = yxyMomentsCommentRepository.findFirst10ByMomentsIdOrderByCreatedDate(yxyMoments.getId());
                yxyMomentsCommentModelLst = new ArrayList<YxyMomentsCommentModel>();
                for (YxyMomentsComment yxyMomentsComment2 : yxyMomentsComment) {
                    YxyMomentsCommentModel yxyMomentsCommentModel = new YxyMomentsCommentModel();
                    yxyMomentsCommentModel.id = yxyMomentsComment2.getId();
                    yxyMomentsCommentModel.userId = yxyMomentsComment2.getUserId();
                    yxyMomentsCommentModel.userNick = yxyMomentsComment2.getUserNick();
                    yxyMomentsCommentModel.avatar = yxyMomentsComment2.getAvatar();
                    yxyMomentsCommentModel.title = yxyMomentsComment2.getReplyerNick();
                    yxyMomentsCommentModel.comment = yxyMomentsComment2.getComment();
                    yxyMomentsCommentModel.BefPre = yxyMomentsComment2.getBefPre();
                    //
                    // 是否自己的班级圈 （前端以此判断是否显示删除）
                    yxyMomentsCommentModel.ownMoments = yxyMomentsCommentModel.userId.equals(currentUserId);
                    yxyMomentsCommentModelLst.add(yxyMomentsCommentModel);

                }
                respModel.yxyMomentsCommentLst = yxyMomentsCommentModelLst;
                respModelLst.add(respModel);
            }
        }
        Page<RespModel> model = new PageImpl<RespModel>(respModelLst, pageable, page.getTotalElements());

        return model;
    }

    @ApiModel(value = "MomentViewReq")
    protected static class ReqModel extends YxyApiPageReqModel {

        // 0 全部 1我的发布
        @ApiModelProperty(value = "类型")
        public Integer type;

        @ApiModelProperty(value = "班级ids")
        public String classId;

        @ApiModelProperty(value = "班级idLst")
        public List<String> classIdLst;

        @Override
        public void autoCheck() {
            Assert.isTrue(type != 0 && type != 1, "类型有误");
        }
    }

    /**
     * 评论列表
     * 
     * @author LiuWeidong
     *
     */
    public class YxyMomentsCommentModel {

        public Boolean ownMoments;
        public String id;
        // 评论用户ID
        public String userId;
        // 姓名
        public String userNick;
        // 头像
        public String avatar;
        // 标题
        public String title;
        // 评论信息
        public String comment;
        // 距离现在多久
        public String BefPre;
    }

    protected static class RespModel extends YxyApiRespModel {
        // ID
        public String id;
        // 创建时间
        public String createdDate;
        // 发送人头像
        public String avator;
        // 发送ID
        public String senderId;
        // 发送昵称
        public String senderNick;
        // 班级昵称
        public String classNick;
        // 发送名称
        public String senderUsername;
        // 发送内容
        public String styleIntro;
        // 发送图片
        public List<String> imgs_60_60;
        // 图片数量
        public Integer imgSize = 0;
        // 删除状态：0/1
        public Integer status;
        // 评论数量
        public Integer commentCount;//
        // 点赞数量
        public Integer praiseCount;//
        // 点赞人信息
        public String praiseUserNickStr;
        // 是否点赞
        public boolean praise;
        // 评论人列表
        public List<YxyMomentsCommentModel> yxyMomentsCommentLst;
        // 是否自己的班级圈
        public boolean ownMoments;
    }

}
